package com.suke.czx.modules.tb.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suke.czx.common.annotation.AuthIgnore;
import com.suke.czx.common.utils.Constant;
import com.suke.czx.modules.sys.entity.SysUser;
import com.suke.czx.modules.sys.service.SysUserService;
import com.suke.czx.modules.tb.entity.*;
import com.suke.czx.modules.tb.service.*;
import com.suke.czx.modules.tb.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.suke.czx.common.utils.R;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import com.suke.czx.common.base.AbstractController;

import javax.annotation.Resource;


/**
 * 小程序用户表
 *
 * @author developer
 * @email developer@163.com
 * @date 2025-05-14 18:45:11
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tb/user")
@Api(value = "TbUserController", tags = "小程序用户表")
@Slf4j
public class TbUserController extends AbstractController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private TbUserFavoriteService tbUserFavoriteService;
    @Resource
    private TbLikesService tbLikesService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private TbOrderInfoService tbOrderInfoService;
    @Resource
    private TbProductService tbProductService;
    @Resource
    private TbUserAddressService tbUserAddressService;

    private final PasswordEncoder passwordEncoder;
    @PostMapping("/login")
    @AuthIgnore
    public R login(@RequestBody LoginVO loginVO) {
        String token;
        String username = loginVO.getUsername();
        String password = loginVO.getPassword();
        String userId = null;
        String userName = null;
        if(StrUtil.isEmpty(username)){
            return R.error("用户名不能为空");
        }
        if(StrUtil.isEmpty(password)){
            return R.error("密码不能为空");
        }
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, username));

        if (sysUser == null) {
            return R.error("用户不存在");
        }

        if (!passwordEncoder.matches(password, sysUser.getPassword())) {
            return R.error("密码错误");
        }

        userId = sysUser.getUserId();
        userName = sysUser.getUsername();

        token = SecureUtil.md5(username + System.currentTimeMillis());

        // 4. 手动绑定用户到 Spring Security（关键！）
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                username,
                null,                // credentials（密码，这里不需要）
                AuthorityUtils.createAuthorityList()  // 随便给个权限
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 保存token
        redisTemplate.opsForValue().set(Constant.AUTHENTICATION_TOKEN + token, userId + "," + userName, Constant.TOKEN_EXPIRE, TimeUnit.SECONDS);
        log.info("用户ID:{},用户名:{},登录成功！  token:{}", userId, userName, token);

        return R.ok().put(Constant.TOKEN, token).put("userInfo", sysUser);
    }

    @PostMapping("/userInfo")
    public R userInfo() {
        String userId = getUserId();
        String favoriteProductIds = "";
        String likeProductIds = "";
        SysUser sysUser = null;
        long buyCount = 0L;
        long sellerCount = 0L;
        long myProductCount = 0L;
        BigDecimal sellerTotalAmount = BigDecimal.ZERO;
        TbUserAddress defaultAddress = null;
        try {
            sysUser = sysUserService.getById(userId);
            // 收藏商品
            LambdaQueryWrapper<TbUserFavorite> tbUserFavoriteLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tbUserFavoriteLambdaQueryWrapper.eq(TbUserFavorite::getUserId, userId);
            tbUserFavoriteLambdaQueryWrapper.select(TbUserFavorite::getProductId);
            List<TbUserFavorite> list = tbUserFavoriteService.list(tbUserFavoriteLambdaQueryWrapper);
            if(!list.isEmpty()){
                // 将 product_id 组成字符串
                favoriteProductIds = list.stream().map(TbUserFavorite::getProductId).map(String::valueOf).collect(Collectors.joining(","));
            }
            // 点赞商品
            LambdaQueryWrapper<TbLikes> tbLikesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tbLikesLambdaQueryWrapper.eq(TbLikes::getUserId, userId);
            tbLikesLambdaQueryWrapper.select(TbLikes::getProductId);
            List<TbLikes> likesList = tbLikesService.list(tbLikesLambdaQueryWrapper);
            if(!likesList.isEmpty()){
                // 将 product_id 组成字符串
                likeProductIds = likesList.stream().map(TbLikes::getProductId).map(String::valueOf).collect(Collectors.joining(","));
            }

            // 获取我上架的商品
            LambdaQueryWrapper<TbProduct> tbProductLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tbProductLambdaQueryWrapper.eq(TbProduct::getUserId, userId);
            tbProductLambdaQueryWrapper.eq(TbProduct::getStatus,"available");
            myProductCount = tbProductService.count(tbProductLambdaQueryWrapper);


            // 获取我买到的订单数量
            LambdaQueryWrapper<TbOrderInfo> orderLqw = new LambdaQueryWrapper<>();
            orderLqw.notIn(TbOrderInfo::getStatus, "closed","cancelled");
            orderLqw.eq(TbOrderInfo::getBuyerId, userId);
            buyCount = tbOrderInfoService.count(orderLqw);

            // 获取我卖出的订单数量
            orderLqw.clear();
            orderLqw.notIn(TbOrderInfo::getStatus, "closed","cancelled");
            orderLqw.eq(TbOrderInfo::getSellerId, userId);
            sellerCount = tbOrderInfoService.count(orderLqw);

            // 赚了多少钱

            sellerTotalAmount = tbOrderInfoService.getSellerTotalAmount(userId);

            // 获取默认地址
            LambdaQueryWrapper<TbUserAddress> tbUserAddressLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tbUserAddressLambdaQueryWrapper.eq(TbUserAddress::getUserId, userId);
            tbUserAddressLambdaQueryWrapper.eq(TbUserAddress::getIsDefault, 1);
            List<TbUserAddress> addressList = tbUserAddressService.list(tbUserAddressLambdaQueryWrapper);
            if(CollectionUtils.isNotEmpty(addressList)){
                defaultAddress = addressList.get(0);
            }
        }catch (Exception e){}

        return R.ok().put("user", sysUser)
                .put("defaultAddress", defaultAddress)
                .put("favoriteProductIds", favoriteProductIds)
                .put("likeProductIds", likeProductIds)
                .put("myProductCount", myProductCount)
                .put("sellerCount", sellerCount)
                .put("sellerTotalAmount", sellerTotalAmount)
                .put("buyCount", buyCount);
    }


}
